package what.api;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;

public class ApiLog {

	public String description;

	public int nClasses = 0, nMethods = 0;

	public HashMap<String, ApiPackage> log = new HashMap<String, ApiPackage>();

	public ApiLog(String description) {
		this.description = description;
	}

	/**
	 * Return the api package that represents the given fully qualified package
	 * name relative to the given parent. If parent is null, name is assumed to
	 * be relative to the root. If necessary create any sub package.
	 */
	public ApiPackage createApiPackage(ApiPackage parent, String packageName) {
		int sep = packageName.indexOf('.');
		if (sep == -1) {
			if (parent == null) {
				ApiPackage result = log.get(packageName);
				if (result == null) {
					result = new ApiPackage(parent, packageName);
					log.put(packageName, result);
				}
				return result;
			}
			ApiPackage result = parent.packages.get(packageName);
			if (result == null) {
				result = new ApiPackage(parent, packageName);
				parent.packages.put(packageName, result);
			}
			return result;
		}
		String subPackageName = packageName.substring(0, sep);
		String subPackageName2 = packageName.substring(sep + 1);
		ApiPackage result1 = createApiPackage(parent, subPackageName);
		ApiPackage result2 = createApiPackage(result1, subPackageName2);
		return result2;
	}

	public static ApiLog create(File logFile) throws IOException {
		ApiLog apiLog = NewApi.createApiLog(logFile);
		apiLog.updateCount(apiLog.log.values());
		return apiLog;
	}

	public void updateCount(Collection<ApiPackage> apiPackages) {
		for (ApiPackage apiPackage : apiPackages) {
			updateCount(apiPackage.packages.values());
			for (ApiClass apiClass : apiPackage.classes.values()) {
				nClasses++;
				ApiPackage temp = apiPackage;
				while (temp != null) {
					temp.nClasses++;
					temp = temp.parent;
				}

				for (ApiMethod apiMethod : apiClass.methods.values())
					for (ApiSignature apiSignature : apiMethod.signatures
							.values()) {
						nMethods++;
						apiClass.nMethods++;
						temp = apiPackage;
						while (temp != null) {
							temp.nMethods++;
							temp = temp.parent;
						}
					}
			}
		}
	}

}
